package trading_strategy;

import trading_strategy.events.EventDispatcher;
import trading_strategy.events.EventManager;
import trading_strategy.events.history.TRTHInstrumentReader;
import trading_strategy.instruments.Future;
import trading_strategy.markets.Market;
import trading_strategy.markets.ZeroTransactionCosts;
import trading_strategy.orders.Brokers;
import trading_strategy.orders.InstrumentOrderBroker;
import trading_strategy.orders.simulation.SimulatedExchange;
import trading_strategy.strategies.MMAStrategy;
import trading_strategy.strategies.PercevalStrategy;

import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.concurrent.Semaphore;

/**
 * Created by IntelliJ IDEA.
 * User: gderoujoux
 * Date: 6 mai 2010
 * Time: 09:15:56
 * To change this template use File | Settings | File Templates.
 */
public class TestPerceval {
    public static void main(String[] args) throws ParseException {
        final Market euronext = new Market(1, "EUR", new ZeroTransactionCosts());
        DateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmm");
        int underlyingId = 2;
        int contractId = 2;

//        if (true) {
//            underlyingId = 3742;
//            contractId = 302790;
//        }
        Future future = new Future(contractId, "CAC_FUT" /*String.valueOf(underlyingId)*/, euronext.getId(), sdf.parse("20100618-1100"), 10, 0.5);

        DateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");

        Calendar start = new GregorianCalendar();
        PercevalStrategy.INTERACTIVE = false;
        start.setTime(sdf2.parse("20100128"));
        //start.setTime(sdf2.parse("20100129"));
        Calendar end = new GregorianCalendar();
        end.setTime(sdf2.parse("20100218"));

//        String baseDir = "\\\\8152wjh\\d$\\hdfdumper\\";
//        start.setTime(sdf2.parse("20100603"));
//        end.setTime(sdf2.parse("20100604"));
        String baseDir = "history/";

        double totalPnl = 0;
        double totalCost = 0;
        while (start.before(end)) {
            final String dateString = sdf2.format(start.getTime());
            try {
                String historyFile = baseDir + dateString + "/" + future.getUnderlyingId() + ".csv";
                if (new File(historyFile).exists()) {
                    EventManager.getInstance().clear();
                    SimulatedExchange.clear();
                    System.out.println("Playing " + dateString);
                    final TRTHInstrumentReader hr = new TRTHInstrumentReader(future, historyFile);

                    SimulatedExchange exchange = SimulatedExchange.getExchange(future); // Instantiates the simulated exchange
                    Brokers.getInstance().registerBroker(future, new InstrumentOrderBroker(exchange)); // The broker

                    //final PercevalStrategy strategy = new PercevalStrategy(start.getTime(), future);
                    final MMAStrategy strategy = new MMAStrategy(start.getTime(), future);
                    strategy.register();

                    // TODO start the market event reader and wait...
                    hr.read();

                    System.out.println("Read");
                    final Semaphore wait = new Semaphore(0);
                    EventManager.getInstance().getDispatcher(EventManager.REPLAY_DISPATCHER).addEvent(new EventDispatcher.TimedRunnable(Long.MAX_VALUE) {
                        @Override
                        public void run() {
                            wait.release();
                        }
                    });
                    wait.acquire();
                    strategy.stop();
                    totalPnl += strategy.getPnL();
                    totalCost += strategy.getTransactionCost();
                    System.out.println("PnL on " + dateString + ": " + strategy.getPnL() + " (" + strategy.getTransactionCost() + ")");
                    System.out.println("NbEvents on " + dateString + ": " + strategy.getEventCounter());
                    strategy.dumpGraph(true);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


            start.add(Calendar.DAY_OF_YEAR, 1);
        }
        System.out.println("Cumulated PnL = " + totalPnl);
        System.out.println("Cumulated Cost = " + totalCost);
        System.exit(0);
    }
}